<?php

namespace App\Repositories;

use App\Models\Users;
use EasyWeChat\Factory;
use function EasyWeChat\Kernel\Support\generate_sign;
use Illuminate\Support\Carbon;
use App\Models\Order;
use App\Models\Orderproduct;
use App\Models\Product;
use App\Models\Userslog;
use DB;
use Log;
class PayRepository
{
    /**
     * 发起微信支付
     *
     * @return Array
     */
    public function pay($openid, $data = [])
    {
        $this->wxpay = app('easywechat.payment');
        $unify = $this->wxpay->order->unify([
            'body' => '支付', //订单说明
            'out_trade_no' => $data['ordersn'], //订单号
            'total_fee' => bcmul($data['price'], 100), //订单金额
            'trade_type' => 'JSAPI',
            'openid' => $openid, // 用户的openid
        ]);
        if ($unify['return_code'] === 'SUCCESS' && !isset($unify['err_code'])) {
            $pay = [
                'appId' => config('wechat.payment.default.app_id'),
                'timeStamp' => (string) time(),
                'nonceStr' => $unify['nonce_str'],
                'package' => 'prepay_id=' . $unify['prepay_id'],
                'signType' => 'MD5',
            ];

            $pay['paySign'] = generate_sign($pay, config('wechat.payment.default.key'));

            return $pay;
        } else {
            $unify['return_code'] = 'FAIL';
            return $unify;
        }
    }
    //微信回调
    public function notify()
    {

        $this->wxpay = app('easywechat.payment');

        return $this->wxpay->handlePaidNotify(
            function ($message, $fail) {
                if ($message['result_code'] === 'FAIL') {
                    logger()->warning('WXPAY_CALLBACK', ['FAIL', $message]);
                    return true;
                } else if ($message['return_code'] === 'SUCCESS') {
                    // TODO: 你的发货逻辑
                    $Sn=substr($message['out_trade_no'] , 0 , 2);
                    $order = Order::where('order_sn', $message['out_trade_no'])->first(); 
                    $Userslog = Userslog::where('order_sn', $message['out_trade_no'])->first(); 
                    $userInfo = Users::where('openid', $message['openid'])->first();
                  
                    if ($Sn=='wx' && $Userslog) {//充值
                        Users::where('openid',$message['openid'])->update(['balance' => $userInfo['balance']+$Userslog['price']]);
                        Userslog::where('id',$Userslog['id'])->update(['state' => 1]);
                    }elseif ($order && $Sn != 'wx') {//订单
                        Order::where('order_sn', $message['out_trade_no'])->update(['state'=>2]);
                        $orderProduct=Orderproduct::where('orderid',$order['id'])->get();
                        foreach ($orderProduct as $key => $value) {
                            $product=Product::where('id',$value['proid'])->first();
                            $xiaoliang=$product['xiaoliang']+$value['num'];
                            Product::where('id',$value['proid'])->update(['xiaoliang' => $xiaoliang]);
                        }
                        Userslog::create(['userid'=>$userInfo['id'],'order_sn'=>$message['out_trade_no'],'price'=>$order['price']+$order['psprice']-$order['yhprice'],'type'=>2,'des'=>'平台微信消费']);
                    }

                    Log::info('==============' . json_encode($message) . '===============');
                    return true;
                }
            }
        );
    }
    //消息推送
    public function send($fromId, $openid)
    {
        $this->wxpay = app('easywechat.mini_program');
        $this->wxpay->template_message->send([
            'touser' => $openid,
            'template_id' => 'zeJ2l3VC61Fuz9lGxg2v4-lE2uMT59Y0ewqJDUvnOZI', //消息模版编号
            'page' => 'index',
            'form_id' => $fromId, //formid 需要小程序前端传
            'data' => [
                'keyword1' => '我草',
                'keyword2' => '无情',
                'keyword3' => '好残忍',
                'keyword4' => '好嗨哦',
            ],
        ]);
    }
    //提现到零钱
    public function toBalance($data)
    {
        $this->wxpay = app('easywechat.payment');
        return $this->wxpay->transfer->toBalance([
            'partner_trade_no' => 'TXYJ' . date('YmdHis') . rand(1111, 9999), // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $data['openid'],
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name' => $data['name'], // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => $data['price'] * 100, // 企业付款金额，单位为分
            'desc' => '佣金提现', // 企业付款操作说明信息。必填
        ]);
    }
    //订单退款到微信零钱
    public function backPay($data=[])
    {
        $this->wxpay = app('easywechat.payment');
        // 参数分别为：商户订单号、商户退款单号、订单金额、退款金额、其他参数
        $this->wxpay->refund->byOutTradeNumber($data['number'],  $data['refundNumber'], $data['totalFee']*100,$data['refundFee']*100, $config = []);
        
        // // Example:
        $result = $this->wxpay->refund->byOutTradeNumber($data['number'], $data['refundNumber'], 20000, 1000, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '商品退款',
            'notify_url'    => 'http://'. $_SERVER['HTTP_HOST'].'/refundBack',
        ]);
        Log::info('==============' . json_encode($result) . '===============');
        return $result;
    }
    // public function refundBack(){
    //     $this->wxpay = app('easywechat.payment');
    //     $response = $this->wxpay->handleRefundedNotify(function ($message, $reqInfo, $fail) {
    //         // 其中 $message['req_info'] 获取到的是加密信息
    //         // $reqInfo 为 message['req_info'] 解密后的信息
          
    //         $order = Order::where('order_sn',$reqInfo['out_trade_no'])->first();

    //         if (!$refund_info || $refund_info->status=='1') { // 如果订单不存在 或者 订单已经退过款了
    //             return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
    //         }
    //         if($message['return_code']=='SUCCESS'){
    //             $update_data = [];
    //             if($reqInfo['refund_status']=='SUCCESS'){
                   
    //             }else{
                    
    //             }
                
    //         }
    //         return true; // 返回 true 告诉微信“我已处理完成”
    //         // 或返回错误原因 $fail('参数格式校验错误');
    //     });

    //     return $response;
    // }
}
